package org.qydjk.console.controller.sys;

import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.SRole;
import org.qydjk.common.pojo.SUser;
import org.qydjk.common.shiro.PasswordHash;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.console.service.ISysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class SUserController extends BaseController {
    @Autowired
    private ISysService sysService;
    @Autowired
    private PasswordHash passwordHash;
    /**
     * “用户管理”入口
     * @return
     */
    @RequestMapping("/manager.do")
    public String userManager(){
        return "admin/user/user";
    }

    /**
     * 用户管理列表
     * @param name
     * @param organizationId
     * @param createdateStart
     * @param createdateEnd
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/dataGrid.do")
    @ResponseBody
    public Object dataGrid(String name, Integer organizationId, String createdateStart,String createdateEnd,Integer page, Integer rows, String sort, String order) throws Exception {
        String sql = "SELECT t.id, t.login_name AS loginName, t.`name`, t.phone, t.`password`," +
                " t.sex, t.age, t.create_time AS createTime, t.user_type AS userType," +
                " t.`status`, t.organization_id AS organizationId," +
                " s.`name` AS organizationName, group_concat(o.`name`) AS rolesList" +
                " FROM s_user t LEFT JOIN s_user_role r ON t.id = r.user_id" +
                " LEFT JOIN s_role o ON r.role_id = o.id" +
                " LEFT JOIN s_organization s ON s.id = t.organization_id where 1 = 1 ";
        if (!StringUtil.isEmptyOrNull(name)) {
            sql += " and t.name like '%" + name + "%'";
        }
        if (organizationId != null) {
            sql += " and t.organization_id = " + organizationId;
        }
        if (!StringUtil.isEmptyOrNull(createdateStart)) {
            sql += " and t.create_time >= '" + createdateStart + "'";
        }
        if (!StringUtil.isEmptyOrNull(createdateEnd)) {
            sql += " and t.create_time <= '" + createdateEnd + "'";
        }
        sql += " GROUP BY t.id";

        String orderBy = " order by t." + StringUtil.underscoreName(sort) + " " + order;
        List<Map<String, Object>> list = baseService.findMapBySQL(sql + orderBy, new HibernatePage(page, rows));

        String cuntSql = "select count(aa.id) from ("+ sql+") aa";

        int total = baseService.getRecordCountSQL(cuntSql);
        return new EasyUIResponse(total,list);
    }

    /**
     * 添加用户页
     *
     * @return
     */
    @GetMapping("/addPage.do")
    public String addPage() {
        return "admin/user/userAdd";
    }

    /**
     * 添加用户
     *
     * @param userVo
     * @return
     */
    @PostMapping("/add.do")
    @ResponseBody
    public Object add(@Valid SUser userVo,String roleIds) throws Exception {
        SUser example = new SUser();
        example.setLoginName(userVo.getLoginName());
        List<SUser> list = baseService.findByExample(example);
        if (list != null && !list.isEmpty()) {
            return renderError("登录名已存在!");
        }
        String salt = StringUtil.getUUID();
        String pwd = passwordHash.toHex(userVo.getPassword(), salt);
        userVo.setSalt(salt);
        userVo.setPassword(pwd);
        userVo.setCreateTime(new Date());
        sysService.addUser(userVo,roleIds);
        return renderSuccess("添加成功");
    }

    /**
     * 编辑用户页
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/editPage.do")
    public String editPage(Model model, Integer id) throws Exception {
        SUser userVo = baseService.get(SUser.class,id);
        List<SRole> rolesList = baseService.findBySQL("select sr.* from s_user_role sur left join s_role sr on sur.role_id = sr.id where sur.user_id = ?",SRole.class,id);
        List<Integer> ids = new ArrayList<Integer>();
        for (SRole role : rolesList) {
            ids.add(role.getId());
        }
        model.addAttribute("roleIds", ids);
        model.addAttribute("user", userVo);
        return "admin/user/userEdit";
    }

    /**
     * 编辑用户
     *
     * @param userVo
     * @return
     */
    @PostMapping("/edit.do")
    @ResponseBody
    public Object edit(@Valid SUser userVo,String roleIds) throws Exception {
        SUser example = new SUser();
        example.setLoginName(userVo.getLoginName());
        List<SUser> list = baseService.findByExample(example);
        if (list != null && !list.isEmpty()) {
            SUser su = list.get(0);
            if(su.getId().intValue() != userVo.getId().intValue()){
                return renderError("登录名已存在!");
            }
        }
        SUser user = baseService.get(SUser.class,userVo.getId());
        // 更新密码
        if (!StringUtil.isEmptyOrNull(userVo.getPassword())) {
            String salt = user.getSalt();
            String pwd = passwordHash.toHex(userVo.getPassword(), salt);
            userVo.setPassword(pwd);
        }else{
            userVo.setPassword(null);
        }
        BeanUtil.copyProperties(userVo,user);
        sysService.updateUser(user,roleIds);
        return renderSuccess("修改成功！");
    }

    /**
     * 修改密码页
     *
     * @return
     */
    @GetMapping("/editPwdPage.do")
    public String editPwdPage() {
        return "admin/user/userEditPwd";
    }

    /**
     * 修改密码
     *
     * @param oldPwd
     * @param pwd
     * @return
     */
    @PostMapping("/editUserPwd.do")
    @ResponseBody
    public Object editUserPwd(String oldPwd, String pwd) throws Exception {
        SUser user = baseService.get(SUser.class,getUserId());
        String salt = user.getSalt();
        if (!user.getPassword().equals(passwordHash.toHex(oldPwd, salt))) {
            return renderError("老密码不正确!");
        }
        user.setPassword(passwordHash.toHex(pwd, salt));
        baseService.update(user);
        return renderSuccess("密码修改成功！");
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @PostMapping("/delete.do")
    @ResponseBody
    public Object delete(Integer id) throws Exception {
        Integer currentUserId = getUserId();
        if (id == currentUserId) {
            return renderError("不可以删除自己！");
        }
        //删除权限
        baseService.excuteSQL("delete from s_user_role where user_id = " + id.intValue());
        //删除用户
        SUser user = new SUser();
        user.setId(id);
        baseService.delete(user);
        return renderSuccess("删除成功！");
    }
}